package com.cw.starter.trace.filter;

/**
 * @author chenw
 * @date 2020/12/17
 */

import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.slf4j.MDC;

import com.alibaba.dubbo.common.Constants;
import com.cw.lang.common.utils.IdGenerator;
import com.cw.starter.trace.filter.constants.TraceConstants;

/**
 */
@Activate(group = {Constants.CONSUMER, Constants.PROVIDER} , order = -9999)
public class GlobalTraceFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String traceId = invocation.getAttachment(TraceConstants.TRACE_ID);
        if(!StringUtils.isBlank(traceId)) {
            RpcContext.getContext().setAttachment(TraceConstants.TRACE_ID,traceId);
        }else { // 第一次发起调用
            traceId = IdGenerator.nextStrId();
            RpcContext.getContext().setAttachment(TraceConstants.TRACE_ID, traceId);
        }
        MDC.put(TraceConstants.TRACE_ID, traceId);
        return invoker.invoke(invocation);
    }
}
